package activity.discuss;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.laoxinwen.app.R;

import java.lang.reflect.Method;

import bean.Topic;
import common.BaseFragment;
import common.Constants;
import common.UserConfig;
import common.VideoWebChromeClient;
import util.LogicUtil;
import util.NetUtil;
import util.ToastUtil;

/**
 * Created by sshong on 15/8/19.
 */
public class FrgWebDiscuss extends BaseFragment {

    private static final int TYPE_RELOAD = 1;

    @id(R.id.webView)
    public WebView webView;

    @id(R.id.fullWebViewContainer)
    private ViewGroup fullWebViewContainer;

    @id(R.id.iv_loading)
    private View loading;

    public VideoWebChromeClient webChromeClient;

    private Topic topic;
    private int discussType;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TYPE_RELOAD:
                    if (NetUtil.isNetworkConnected(getActivity())) {
                        webView.loadUrl(getUrl());
                    } else {
                        ToastUtil.showShortToast(Constants.MSG_NET_ERROR);
                    }
                    break;
            }
        }
    };

    private String getUrl() {
        return LogicUtil.getDiscussUrl(discussType, topic);
    }

    public void setData(Topic topic, int type) {
        this.topic = topic;
        this.discussType = type;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_discuss, container, false);
        loadView(root);

        setWebView();
        webView.loadUrl(getUrl());
        return root;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //退出时夜间模式反色
        if (UserConfig.isNightMode()) {
            try {
                Class clsWebSettingsClassic = getClass().getClassLoader().loadClass("android.webkit.WebSettingsClassic");
                Method md = clsWebSettingsClassic.getMethod("setProperty", String.class, String.class);
                md.invoke(webView.getSettings(), "inverted", "false");
                md.invoke(webView.getSettings(), "inverted_contrast", "1");
            } catch (Exception e) {
            }
        }
        webView.destroy();
    }

    @SuppressLint("JavascriptInterface")
    private void loadErrorHtml() {
        webView.clearHistory();
        webView.loadUrl(Constants.ERROR_HTML);
        webView.addJavascriptInterface(new Object() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @JavascriptInterface
            public void jsreload(String content) {
                handler.sendEmptyMessage(TYPE_RELOAD);
            }
        }, "Android");
    }

    @SuppressLint({"SetJavaScriptEnabled", "NewApi"})
    private void setWebView() {
        webChromeClient = new VideoWebChromeClient(webView, fullWebViewContainer, (VideoWebChromeClient.VideoFullScreenHandler) getActivity());
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                cancelLoading();
                super.onPageFinished(view, url);
                /*String js = "var script = document.createElement('script');";
                //js += "script.src='" + Constants.DISCUSS_JS + "';";
                js += "script.src='http://192.168.1.102:8085/assets/js/discuss.js';";
                js += "document.body.appendChild(script);";
                //js = "document.documentElement.style['-webkit-filter'] = 'invert(1)';";
                webView.loadUrl("javascript:" + js);*/
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                showLoading();
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (!Constants.ERROR_HTML.equals(failingUrl)) {
                    loadErrorHtml();
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        WebSettings ws = webView.getSettings();
        webView.setVerticalScrollBarEnabled(true);
        webView.setHorizontalScrollBarEnabled(false);
//        webView.setBackgroundColor(Color.TRANSPARENT);
        ws.setUseWideViewPort(true);
        ws.setAppCacheEnabled(true);
        ws.setSaveFormData(true);
        ws.setUseWideViewPort(true);
        ws.setJavaScriptEnabled(true);
        //夜间模式反色
        if (UserConfig.isNightMode()) {
            try {
                Class clsWebSettingsClassic = getClass().getClassLoader().loadClass("android.webkit.WebSettingsClassic");
                Method md = clsWebSettingsClassic.getMethod("setProperty", String.class, String.class);
                md.invoke(webView.getSettings(), "inverted", "true");
                md.invoke(webView.getSettings(), "inverted_contrast", "1");
            } catch (Exception e) {
            }
        }
    }

    private void cancelLoading() {
        loading.setVisibility(View.GONE);
    }

    private void showLoading() {
        loading.setVisibility(View.VISIBLE);
    }
}
